package com.qipay.api.callback.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.qipay.api.util.CommonUtil;
import com.qipay.baas.model.Holiday;
import com.qipay.baas.model.Order;
import com.qipay.baas.model.Sp;
import com.qipay.mapper.HolidayMapper;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.sp.SpService;
import com.qipay.utils.DateUtils;
import com.qipay.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 辉付
 */
@RestController
@RequestMapping("/callback/v1")
public class CallbackController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    OrderService orderService;
    @Autowired
    HolidayMapper holidayMapper;
    @Autowired
    SpConfigService spConfigService;

    /**
     * 测试回调地址
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/test/native", method = RequestMethod.POST)
    private String unionCreate(
            HttpServletRequest request,HttpServletResponse response) {
        return "SUCCESS";
    }

    /**
     * a577回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/a577/wx")
    private String a577(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if(params!=null){
            String tradeNo = params.get("out_order_id").toString();
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }
            //校验回调ip
            if(getSpCallbackIp(request,order)){
                logger.info("ip不在白名单： " + order.getTradeNo());
                return "ip不在白名单";
            }
            //验签
            Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
            String key = keyValues.get("key").toString();
            String fromSign = params.remove("sign").toString();
            String mySign = "";
            if(fromSign.equals(mySign)){
                //校验订单状态
                if (order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()==OrderStateEnum.WAITING.getType()){
                    orderService.setOrderSuccess(order.getId(), null);
                }
                return "success";
            }else {
                logger.info("回调失败：签名sign不一致，tradeNo="+tradeNo);
            }
        }
        return "fail";
    }
    /**
     * 验证回调ip
     * @param request
     * @param order
     * @return
     */
    public Boolean getSpCallbackIp(HttpServletRequest request, Order order) {
        String ip = CommonUtil.getLocalIp(request);
        if(ip==null){
            ip = CommonUtil.getIp2(request);
        }
        logger.info("huitiao获取ip=="+ip);
        String callbackIps = order.getSpMchId();
        if(callbackIps!=null&&callbackIps.contains(ip)){
            return false;//在白名单之内，过
        }
        return true;
    }
    /**
     * 测试个码回调
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/monitor/order/status")
    private String notify(
            HttpServletRequest request,
            HttpServletResponse response
    ){

        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        //************日志录入*********
        Holiday holiday = new Holiday();
        holiday.setDate(DateUtils.sdf.format(new Date()));
        holiday.setName(params.toString());
        holiday.setIsHoliday((byte)1);
        holidayMapper.insert(holiday);
        //************业务处理*********
        /**
         *就该通道取五分钟内的第一笔，执行器那边进行判定（五分钟内有未支付订单，不让下单），
         *页面搞一个3分50秒订单失效（95%付款订单所需时间是1分~2分）
         * 超过的单，需人工补单，加入掉单表
         */
        String payCount = params.get("payCount").toString();//到账金额
        //到账时间,暂时先不用，根据系统时间（因为执行器下单的时候是根据系统时间判定的五分钟，请求误差就包括在5分钟之内，毕竟掉单是小概率）
        String payTime = params.get("payTime").toString();
        String channelId = params.get("channelId").toString();//通道id
        List<Order> orders = orderService.selectBySpidAmountTime(Long.valueOf(channelId)
                ,new BigDecimal(payCount).multiply(new BigDecimal("100")).intValue());
        if(orders!=null&&orders.size()>0){
            try {
                orderService.setOrderSuccess(orders.get(orders.size()-1),null);
            }catch (Exception e){
                logger.info(orders.get(orders.size()-1).getTradeNo()+":"+e.getMessage());
            }
        }else {
            //录入掉单表，方便人工核对
            holiday = new Holiday();
            holiday.setDate(DateUtils.sdf.format(new Date()));
            holiday.setName(params.toString());
            holiday.setIsHoliday((byte)88);
            holidayMapper.insert(holiday);
        }
        //************结果集的返回*********
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg","SUCCESS");
        jsonObject.put("code","200");
        jsonObject.put("data","");
        return jsonObject.toJSONString();
    }
    @Autowired
    SpService spService;
    /**
     * 回调登陆
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/monitor/login")
    private String login(
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        //************日志录入*********
        Holiday holiday = new Holiday();
        holiday.setDate(DateUtils.sdf.format(new Date()));
        holiday.setName(params.toString());
        holiday.setIsHoliday((byte)0);
        holidayMapper.insert(holiday);
        //校验登陆
        String username = params.get("username").toString();
        String password = params.get("password").toString();

        JSONObject jsonObject = new JSONObject();
        if(username.equals(password)){
            Sp sp = spService.get(Integer.valueOf(username));
            if(sp!=null){
                //标记登陆
                sp.setMchId("0000");//"0000"表示登陆成功，禁用之后重置，要重新登陆
                spService.update(sp);

                jsonObject.put("isLogin",true);
                jsonObject.put("channelId",username);
            }
        }
        return jsonObject.toJSONString();
    }
    /**
     * 猛虎
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/menghu/native")
    private String menghu(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if(params!=null){
            String tradeNo = params.get("out_trade_no").toString();
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }
            if ("CODE_SUCCESS".equals(params.get("callbacks"))){
                if (order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()==OrderStateEnum.WAITING.getType()){
                    orderService.setOrderSuccess(order.getId(), null);
                }
                return "success";
            }
        }
        return "success";
    }
    /**
     * 高欣
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/gaoxin/native")
    private String gaoxin(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if(params!=null){
            String tradeNo = params.get("tradeNo").toString();
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }
            if ("200".equals(params.get("code"))){
                if (order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()==OrderStateEnum.WAITING.getType()){
                    orderService.setOrderSuccess(order.getId(), null);
                }
                return "success";
            }
        }
        return "success";
    }

    @RequestMapping(value = "/deshun/native")
    private String deshun(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("customno").toString();
        Order order = orderService.getByTradeNo(tradeNo);
        if (order == null) {
            logger.info("回调失败：查无此订单=" + tradeNo);
            return "FAIL";
        }
        int realAmount = new BigDecimal(params.get("money").toString()).multiply(new BigDecimal("100")).intValue();
        int ourAmount = order.getAmount();
        if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
            if (ourAmount-realAmount  <= 50 ) {
                orderService.setOrderSuccess(order.getId(), null);
            }
        }
        return "OK";
    }

    @RequestMapping(value = "/yinhe/native")
    private String yinhe(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("orderNumber").toString();
        Order order = orderService.getByTradeNo(tradeNo);
        if (order == null) {
            logger.info("回调失败：查无此订单=" + tradeNo);
            return "FAIL";
        }
        int realAmount = new BigDecimal(params.get("money").toString()).multiply(new BigDecimal("100")).intValue();
        int ourAmount = order.getAmount();
        if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
            if (ourAmount-realAmount  <= 50 ) {
                orderService.setOrderSuccess(order.getId(), null);
            }
        }
        return "succeed";
    }

    /**
     * 如意支付
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/ruyi/native")
    private String ruyi(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if ("00".equals(params.get("returnCode"))) {
            String tradeNo = params.get("tradeNo").toString();
            Order order = orderService.getByTradeNo(tradeNo);
            if (order == null) {
                logger.info("回调失败：查无此订单=" + tradeNo);
                return "FAIL";
            }
            int realAmount = new BigDecimal(params.get("amount").toString()).multiply(new BigDecimal("100")).intValue();
            int ourAmount = order.getAmount();
            if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
                if (realAmount - ourAmount == 0 ) {
                    orderService.setOrderSuccess(order.getId(), null);
                }else {
                    return "FAIL";
                }
            }

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","1");
        jsonObject.put("data","success");
        jsonObject.put("info","success");
        return jsonObject.toJSONString();
    }


    /**
     * 大富
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dafu/native")
    private String dafu(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        if ("success".equals(params.get("status"))) {
            String tradeNo = params.get("sh_order").toString();
            Order order = orderService.getByTradeNo(tradeNo);
            if (order == null) {
                logger.info("回调失败：查无此订单=" + tradeNo);
                return "FAIL";
            }
            int realAmount = new BigDecimal(params.get("money").toString()).multiply(new BigDecimal("100")).intValue();
            int ourAmount = order.getAmount();
            if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
                if (realAmount - ourAmount == 0 ) {
                    orderService.setOrderSuccess(order.getId(), null);
                }
            }
            return "success";
        }
        return "success";
    }

    /**
     * 蚂蚁
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/tangchao/native")
    private String tangchao(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("out_trade_no").toString();
        Order order = orderService.getByTradeNo(tradeNo);
        if (order == null) {
            logger.info("回调失败：查无此订单=" + tradeNo);
            return "FAIL";
        }
        int realAmount = new BigDecimal(params.get("real_price").toString()).multiply(new BigDecimal("100")).intValue();
        int ourAmount = order.getAmount();
        if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
            if (ourAmount-realAmount  <= 50 ) {
                orderService.setOrderSuccess(order.getId(), null);
            }
        }
        return "SUCCESS";
    }

    /**
     * 霸王
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/bawang/native")
    private String bawang(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("orderid").toString();
        Order order = orderService.getByTradeNo(tradeNo);
        if(order==null) {
            logger.info("回调失败：查无此订单="+tradeNo);
            return "fail";
        }
        Integer price = new BigDecimal(params.get("amount").toString()).multiply(new BigDecimal("100")).intValue();
        if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
            if(order.getAmount().equals(price)){
                orderService.setOrderSuccess(order.getId(), null);
                return "OK";
            }
        }

        return "OK";
    }

    /**
     * 霸王
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dasheng/native")
    private String dasheng(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("orderid").toString();
        Order order = orderService.getByTradeNo(tradeNo);
        if(order==null) {
            logger.info("回调失败：查无此订单="+tradeNo);
            return "fail";
        }
        if(!"00".equals(params.get("returncode").toString())){
            return "ok";
        }
        Integer price = new BigDecimal(params.get("amount").toString()).multiply(new BigDecimal("100")).intValue();
        if(order.getState()== OrderStateEnum.NOTPAY.getType()||order.getState()== OrderStateEnum.WAITING.getType()){
            if(order.getAmount().equals(price)){
                orderService.setOrderSuccess(order.getId(), null);
                return "ok";
            }
        }

        return "ok";
    }
}